package p.sglmsn.top.ext.wx.iface.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import p.sglmsn.top.ext.wx.enums.MethodEnum;
import p.sglmsn.top.ext.wx.iface.EventInterface;
import p.sglmsn.top.ext.wx.iface.PhysicalInterface;
import p.sglmsn.top.ext.wx.iface.ReturnInterface;
import p.sglmsn.top.ext.wx.iface.WeCharService;
import p.sglmsn.top.ext.wx.service.WeChatService;
import p.sglmsn.top.ext.wx.wxext.http.SendDto;

import java.math.BigDecimal;
import java.util.Optional;

@Component
@Slf4j
public class WeCharServiceImpl implements WeCharService {

    @Override
    public ReturnInterface send(PhysicalInterface anInterface) {
        return null;
    }

    @Override
    public EventInterface eventTrigger(EventInterface eventInterface) {
        return null;
    }

    @Override
    public ReturnInterface receivedTheNews(JSONObject json) {
//        log.info("收到请求:{}", informationReceived);
        JSONObject data = json.getJSONObject("data");
        //这大概是群聊
        if (StrUtil.isNotBlank(data.getString("memid"))) {
            return null;
        }
        Optional.ofNullable(data.getString("msg")).ifPresent(s -> {
            // TODO: 2021/2/18 回复信息
        });
        return null;
    }

    @Override
    public ReturnInterface receivedTransfer(JSONObject json) {
        Document document = XmlUtil.parseXml(json.getJSONObject("data").getString("msg"));
        NodeList transcationid = document.getElementsByTagName("transferid");
        NodeList paysubtype = document.getElementsByTagName("paysubtype");
        NodeList pay_memo = document.getElementsByTagName("pay_memo");
        String feedesc = document.getElementsByTagName("feedesc").item(0).getTextContent();
        String remark = null;
        if (pay_memo.getLength() > 0) {
            remark = pay_memo.item(0).getTextContent();
        }
        BigDecimal money = new BigDecimal(feedesc.substring(1)); //金额
        String textContent1 = paysubtype.item(0).getTextContent();
        if (StrUtil.equals(textContent1, "3")) {
            // 收款成功的通知
            log.info("收款:{}", json);
        } else {
            String textContent = transcationid.item(0).getTextContent();
            MethodEnum.收款.exec(new SendDto().setTransferid(textContent));
        }
        return null;
    }

    @Override
    public ReturnInterface login(JSONObject json) {
        SendDto dto = new SendDto();
        MethodEnum.获取授权.exec(dto);
        WeChatService.LOGIN_ACCOUNT.add(dto.getMyid());
        WeChatService.DICT.set(dto.getMyid(), dto.getPid());
        return null;
    }
}
